package com.insist.framework;

import com.insist.util.FasterJsonTools;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by INSIST on 2016/6/25.
 */
public class CmmAuthorizationFilter extends AuthorizationFilter {


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpResponse ;
        HttpServletRequest httpRequest;
        Map<String, Object> map = new HashMap<String, Object>();
        httpResponse = WebUtils.toHttp(response);
        httpRequest = WebUtils.toHttp(request);

        if(isLoginRequest(httpRequest, httpResponse)){
            return true;
        }else if(!"XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With"))){
            saveRequestAndRedirectToLogin(request, response);
            return false;
        } else {
            WebUtils.saveRequest(request);
            map.put("requestUri", httpRequest.getRequestURI());
            httpResponse.setStatus(200, "redirect");
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;

            try{
                out = httpResponse.getWriter();
                CmmBaseResponse ret = new CmmBaseResponse();
                ret.setMessage("");
                ret.setSuccess(false);
                out.append(FasterJsonTools.writeValueAsString(ret));
            }catch(IOException e){
                e.printStackTrace();
            }finally {
                if (out != null) {
                    out.close();
                }
            }
            return false;
        }
    }

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws IOException {
        Subject subject = getSubject(request, response);
        Object o = subject.getPrincipal();
        if(o==null) {
            return false;
        }else {
            return true;
        }
    }
}
